const db = require('../config/db.config');

class Chat {
    // 创建新会话
    static async createSession(userId, sessionName) {
        const [result] = await db.execute(
            'INSERT INTO chat_sessions (user_id, session_name) VALUES (?, ?)',
            [userId, sessionName]
        );
        return result.insertId;
    }

    // 获取用户的所有会话
    static async getSessions(userId) {
        const [rows] = await db.execute(
            'SELECT * FROM chat_sessions WHERE user_id = ? AND is_deleted = 0 ORDER BY updated_at DESC',
            [userId]
        );
        return rows;
    }

    // 获取单个会话详情
    static async getSessionById(sessionId, userId) {
        const [rows] = await db.execute(
            'SELECT * FROM chat_sessions WHERE session_id = ? AND user_id = ? AND is_deleted = 0',
            [sessionId, userId]
        );
        return rows[0];
    }

    // 重命名会话
    static async renameSession(sessionId, userId, newName) {
        const [result] = await db.execute(
            'UPDATE chat_sessions SET session_name = ? WHERE session_id = ? AND user_id = ?',
            [newName, sessionId, userId]
        );
        return result.affectedRows > 0;
    }

    // 删除会话（软删除）
    static async deleteSession(sessionId, userId) {
        const [result] = await db.execute(
            'UPDATE chat_sessions SET is_deleted = 1 WHERE session_id = ? AND user_id = ?',
            [sessionId, userId]
        );
        return result.affectedRows > 0;
    }

    // 保存对话消息
    static async saveMessage(sessionId, userId, role, content) {
        const [result] = await db.execute(
            'INSERT INTO chat_messages (session_id, user_id, role, content) VALUES (?, ?, ?, ?)',
            [sessionId, userId, role, content]
        );
        return result.insertId;
    }

    // 获取会话的所有消息
    static async getMessages(sessionId, userId) {
        const [rows] = await db.execute(
            'SELECT * FROM chat_messages WHERE session_id = ? AND user_id = ? ORDER BY created_at ASC',
            [sessionId, userId]
        );
        return rows;
    }
}

module.exports = Chat; 